import os
import threading
from queue import Queue
from pathlib import Path
from typing import Dict
import requests
import logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)


class ImageAnalyzer:
    def __init__(
        self,
        api_key: str = os.getenv("DASHSCOPE_API_KEY") or "",
        model: str = "qwen-vl-max"
    ):
        self.api_key = api_key
        self.model = model

    def analyze_pdf_directory_http(
        self,
            local_base_dir_raw: str,
            base_url: str,
            prompt_text: str = "请根据这些图片描述整个 PDF 内容") -> Dict[str, str]:
        """
        并发分析整个 PDF 图片目录，每个 PDF 一个线程，使用 HTTP POST 调用 DashScope API。
        返回 {pdf_name: overall_description}。
        """
        local_base_dir = Path(local_base_dir_raw)
        results = {}
        queue = Queue()

        def worker(pdf_dir: Path):
            pdf_name = pdf_dir.name
            messages_content = []

            # 收集该 PDF 目录下所有图片的 URL
            for img_file in sorted(pdf_dir.iterdir()):
                if img_file.is_file() and img_file.suffix.lower() in [".png", ".jpg", ".jpeg", ".webp"]:
                    url = f"{base_url}/{pdf_name}/{img_file.name}"
                    logger.info(f"{pdf_name}=>{url}")
                    messages_content.append(
                        {"type": "image_url", "image_url": {"url": url}})

            # 最后加上 prompt_text
            messages_content.append({"type": "text", "text": prompt_text})

            payload = {
                "model": self.model,
                "messages": [{"role": "user", "content": messages_content}]
            }
            headers = {
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            }

            # HTTP POST 请求
            response = requests.post(
                "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
                json=payload,
                headers=headers
            )
            data = response.json()
            # 取模型返回文本
            content = data["choices"][0]["message"]["content"] if "choices" in data else str(
                data)
            queue.put((pdf_name, content))

        threads = []
        for pdf_dir in sorted(local_base_dir.iterdir()):
            if pdf_dir.is_dir():
                t = threading.Thread(target=worker, args=(pdf_dir,))
                t.start()
                threads.append(t)

        for t in threads:
            t.join()

        # 收集结果
        while not queue.empty():
            pdf_name, description = queue.get()
            results[pdf_name] = description

        return results
